package cn.itcast.zuoyebang;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;

import cn.itcast.zuoyebang.fragment.Const;
import cn.itcast.zuoyebang.utils.PreferenceUtils;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText userName, pwd, pwd2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        TextView backBtn = findViewById(R.id.register_back);
        Button registerBtn = findViewById(R.id.register_btn);

        userName = findViewById(R.id.user_name_tv);
        pwd = findViewById(R.id.pwd_tv);
        pwd2 = findViewById(R.id.pwd_repeat_tv);

        backBtn.setOnClickListener(this);
        registerBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {


        switch (view.getId()) {
            case R.id.register_back:
                finish();
                break;
            case R.id.register_btn:
                if(userName.getText().toString().equals("")) {
                    Snackbar.make(view, "请输入用户名", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if(pwd.getText().toString().equals("")  || pwd2.getText().toString().equals("") ) {
                    Snackbar.make(view, "请输入密码", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                if(pwd.getText().toString().equals(pwd2.getText().toString())) {
                    // 如果(密码和确认密码)相等
                    // 记录用户的注册信息  跳转到已登录界面
                    if(PreferenceUtils.getInstance(this).isUserExist(userName.getText().toString())){
                        Snackbar.make(view,"用户名已存在",Snackbar.LENGTH_SHORT).show();
                    } else {
                        PreferenceUtils.getInstance(this).savePassword(userName.getText().toString(),pwd.getText().toString());
                    }

                    Snackbar.make(view,"注册成功",Snackbar.LENGTH_SHORT).show();
                    Intent data = new Intent();
                    data.putExtra(Const.NEW_USER_NAME,userName.getText().toString());//获取用户名（跳转页面后自动填充）
                    setResult(RESULT_OK,data);
                    finish();
                } else {
                    Snackbar.make(view, "两次密码不一致", Snackbar.LENGTH_SHORT).show();
                    return;
                }
                break;
        }
    }




}
